<template>
  <div>
    <a-tabs v-model="tabName" @change="callback">
      <a-tab-pane v-for="name in title" :key="name" :tab="name">
        <a-spin :spinning="loading">
          <a-form
            :form="form"
            @submit="handleSubmit"
            :loading="loading"
          >
            <a-form-item self-update v-for="(item, index) in formTable[name]" :key="index" :label="item.title" style="margin: 0;">
              <a-input
                v-if="!item.type || item.type === 'textarea'"
                :type="item.type ? 'textarea' : 'input'"
                :rows="12"
                v-decorator="[
                  index,
                  {rules: [item.required ? { required: true, message: item.errMessage } : {}], validateTrigger: 'blur', initialValue: item.value}
                ]"
              />
              <a-upload
                v-else-if="item.type === 'file'"
                name="file"
                :action="`${BASE_URL}/community/tool/save_file?fileType=${name}@${index}`"
                :headers="{
                  authorization: token
                }"
                :data="{
                  status: 2
                }"
                @change="handleChange"
                style="margin-bottom: 10px"
              >
                <a-button> <a-icon type="upload" /> 上传文件 </a-button>
              </a-upload>
            </a-form-item>
            <a-form-item style="margin-top:24px">
              <a-button
                size="large"
                type="primary"
                htmlType="submit"
              >{{ $t('submit') }}</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import {
  formTable,
  title,
  addConfig
} from '../js/oauthConfig'
import {
  update
} from '@/api/oauthConfig'
export default {
  name: 'OConfigModal',
  data () {
    return {
      // 表单
      formTable,
      title,
      form: this.$form.createForm(this),
      loading: false,
      BASE_URL: process.env.VUE_APP_API_BASE_URL,
      tabName: 'wechat'
    }
  },
  props: {
    formName: {
      type: String,
      default: () => {
        return 'wechat'
      }
    },
    info: {
      type: [Array, Object],
      default: () => {
        return {}
      }
    }
  },
  computed: {
    token () {
      return this.$store.getters.token
    }
  },
  mounted () {
    this.initConfig()
  },
  watch: {
    info (value) {
      this.initConfig()
    }
  },
  methods: {
    callback (key) {
      if (this.info.config_id) {
        this.$message.warning('编辑更新时不可更换 Tabs页')
        this.tabName = this.info.config_type
      }
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields }
      } = this
      validateFields(Object.keys(this.formTable[this.tabName]), { force: true }, (err, values) => {
        if (!err) {
          const Params = { ...values }
          let index = 0
          Object.keys(this.formTable).some(k => {
            if (k === this.tabName) {
              Params.config_type = index
              return true
            }
            index = index + 1
          })
          // 设置证书
          Params.cert_private = this.formTable[this.tabName].cert_private?.value || ''
          Params.cert_public = this.formTable[this.tabName].cert_public?.value || ''
          if (!this.info.config_id) {
            addConfig({
              config_name: Params.config_name,
              config: Params
            }).then(res => {
              this.$message[res.code === 200 ? 'success' : 'warning'](res.msg)
              if (res.code === 200) {
                this.initConfig()
                this.$emit('close', {
                  type: 'create',
                  data: {
                    config_id: res.items.config_id,
                    config_name: Params.config_name,
                    config_type: Params.config_type,
                    config_info: Params
                  }
                })
              }
            })
          } else {
            update({
              config_id: this.info.config_id,
              config_name: Params.config_name,
              config: Params
            }).then(res => {
              this.$message[res.code === 200 ? 'success' : 'warning'](res.msg)
              this.$emit('close', {
                type: 'update',
                data: {
                  config_id: this.info.config_id,
                  config_name: Params.config_name,
                  config_type: this.info.config_type,
                  config_info: Params
                }
              })
            })
          }
        }
      })
    },
    // 上传文件回调
    handleChange (info) {
      // code ...
      if (info.file.status === 'done') {
        this.$message[info.file.response.code === 200 ? 'success' : 'warning'](info.file.response.msg)
        if (info.file.response.code !== 200) {
          info.fileList.pop()
          return
        }
        let type = info.file.xhr.responseURL.split('=')
        let key = null
        if (type.length > 1) {
          [type, key] = type[1].split('@')
          this.formTable[type][key].value = info.file.response.items[0].resources_path
        }
      }
    },
    // 初始化配置信息
    initConfig () {
      this.tabName = this.info.config_type || 'wechat'
      if (this.info.config_id && this.info.config_id !== '') {
        for (const index in this.info?.config_info) {
          if (this.formTable[this.tabName][index]) {
            this.formTable[this.tabName][index].value = this.info.config_info[index] || ''
          }
        }
      } else {
        Object.keys(this.formTable).map(k => {
          for (const formTableElementKey in this.formTable[k]) {
            this.formTable[k][formTableElementKey].value = ''
          }
        })
      }
      this.form.resetFields()
    }
  }
}
</script>

<style scoped>
</style>
